package com.guigu.alibaba.controller;


import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.guigu.springcloud.common.CommonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
@RequestMapping("/nacos")
public class OrderByRibbonController {

    @Value("${service-url.nacos-user-service}")
    private String serviceUrl;

    @Autowired
    private RestTemplate restTemplate;

    @GetMapping("/getPayment/{id}")
    // @SentinelResource(value = "getPayment") // 什么都不配置
    // @SentinelResource(value = "getPayment", fallback = "handleFallback") // 配置异常处理
    @SentinelResource(value = "getPayment", fallback = "handleFallback", blockHandler = "blockHandler")
    public CommonResult getPort(@PathVariable("id") Long id) {
        if (id == 5) {
            throw new IllegalArgumentException("非法参数异常");
        }
        CommonResult result = restTemplate.getForObject(serviceUrl + "/nacosOpenfeign/" + id, CommonResult.class);
        if (result.getData() == null) {
            throw new NullPointerException("空指针异常");
        }
        return result;
    }

    // 程序中的异常处理
    public CommonResult handleFallback(@PathVariable("id") Long id,
                                       Throwable throwable) {
        return CommonResult.voData(444, "异常报错： " + throwable.getMessage(), null);
    }

    // 服务中的降级处理: sentinel中的配置违规
    public CommonResult blockHandler(@PathVariable("id") Long id,
                                     BlockException ex) {
        return CommonResult.voData(400, "服务熔断：" + ex.getMessage(), null);
    }
}
